package com.example.demo.demos.gui;

import com.example.demo.demos.entity.SendMail;
import com.example.demo.demos.entity.UploadList;
import com.example.demo.demos.repository.SendMailRepository;
import com.example.demo.demos.repository.UploadListRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Component;

import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

@Component
public class Page3Panel extends JPanel {
    private JTable table;
    private JScrollPane scrollPane;
    private JTextField searchField;
    private JButton searchButton;
    private JComboBox<String> pageSizeComboBox;
    private JLabel currentPageLabel;
    private JLabel totalPagesLabel;
    private JButton prevButton;
    private JButton nextButton;
    private JButton[] pageButtons = new JButton[3]; // 最近三页
    private int currentPage = 0;
    private int pageSize = 10;
    private int totalPages = 0;

    @Autowired
    private SendMailRepository sendMailRepository;

    @Autowired
    private UploadListRepository uploadListRepository;

    public Page3Panel() {
        setLayout(new BorderLayout());

        // 搜索区域
        JPanel searchPanel = new JPanel();
        searchField = new JTextField(20);
        searchButton = new JButton("搜索");
        searchPanel.add(new JLabel("搜索:"));
        searchPanel.add(searchField);
        searchPanel.add(searchButton);

        // 分页控件
        JPanel paginationPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        JLabel pageSizeLabel = new JLabel("每页:");
        pageSizeComboBox = new JComboBox<>(new String[]{"10", "20", "50", "100"});
        currentPageLabel = new JLabel("第 1 页");
        totalPagesLabel = new JLabel("共 0 页");

        // 初始化页码按钮
        for (int i = 0; i < 3; i++) {
            pageButtons[i] = new JButton();
            pageButtons[i].addActionListener(e -> {
                int pageNum = Integer.parseInt(((JButton) e.getSource()).getText());
                currentPage = pageNum - 1;
                loadPage(currentPage);
            });
            paginationPanel.add(pageButtons[i]);
        }

        // 上一页/下一页按钮
        prevButton = new JButton("上一页");
        nextButton = new JButton("下一页");

        // 添加到面板
        paginationPanel.add(pageSizeLabel);
        paginationPanel.add(pageSizeComboBox);
        paginationPanel.add(currentPageLabel);
        paginationPanel.add(totalPagesLabel);
        paginationPanel.add(prevButton);
        paginationPanel.add(nextButton);

        // 表格
        table = new JTable();
        setupTableRenderer();
        scrollPane = new JScrollPane(table);

        add(searchPanel, BorderLayout.NORTH);
        add(scrollPane, BorderLayout.CENTER);
        add(paginationPanel, BorderLayout.SOUTH);

        // 搜索事件
        searchButton.addActionListener(e -> {
            currentPage = 0;
            loadPage(currentPage);
        });

        // 每页数量变化
        pageSizeComboBox.addActionListener(e -> {
            pageSize = Integer.parseInt((String) pageSizeComboBox.getSelectedItem());
            currentPage = 0;
            loadPage(currentPage);
        });
        table.addMouseListener(new java.awt.event.MouseAdapter() {
            @Override
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                int row = table.rowAtPoint(evt.getPoint());
                int col = table.columnAtPoint(evt.getPoint());

                if (row >= 0 && col == 6) { // 第7列是“发送结果”列（索引从0开始）
                    String result = (String) table.getValueAt(row, col);
                    JOptionPane.showMessageDialog(Page3Panel.this, "发送结果:\n" + result, "发送结果", JOptionPane.INFORMATION_MESSAGE);
                }
            }
        });
        // 上一页
        prevButton.addActionListener(e -> {
            if (currentPage > 0) {
                currentPage--;
                loadPage(currentPage);
            }
        });

        // 下一页
        nextButton.addActionListener(e -> {
            if (currentPage < totalPages - 1) {
                currentPage++;
                loadPage(currentPage);
            }
        });
    }

    public void loadPage(int page) {
        String search = searchField.getText();
        List<UploadList> data = fetchDataFromServer(search, page);
        updateTable(data);
        updatePaginationUI();
    }

    private List<UploadList> fetchDataFromServer(String search, int page) {
        return uploadListRepository.findByMsgContainingOrderByIdDesc(search, PageRequest.of(page, pageSize)).getContent();
    }

    private void updateTable(List<UploadList> data) {
        String[] columns = {"ID", "邮箱", "文件地址", "目录", "执行时间","size", "发送结果", "入库日期"};
        Object[][] rows = new Object[data.size()][8];
        for (int i = 0; i < data.size(); i++) {
            UploadList entity = data.get(i);
            rows[i][0] = entity.getId();
            rows[i][1] = entity.getEmail();
            rows[i][2] = entity.getFileName();
            rows[i][3] = entity.getPath();
            rows[i][4] = entity.getTime();
            rows[i][5] = entity.getSize();
            rows[i][6] = entity.getMsg();
            rows[i][7] = entity.getCreatedAt();
        }
        table.setModel(new DefaultTableModel(rows, columns));
    }

    private void updatePaginationUI() {
        // 获取总页数
        String search = searchField.getText();
        totalPages = sendMailRepository.findByMsgContainingOrderByIdDesc(search, PageRequest.of(0, pageSize)).getTotalPages();

        currentPageLabel.setText("第 " + (currentPage + 1) + " 页");
        totalPagesLabel.setText("共 " + totalPages + " 页");

        // 更新页码按钮
        for (int i = 0; i < 3; i++) {
            int pageNum = currentPage - 1 + i;
            if (pageNum >= 0 && pageNum < totalPages) {
                pageButtons[i].setText(String.valueOf(pageNum + 1));
                pageButtons[i].setVisible(true);
            } else {
                pageButtons[i].setVisible(false);
            }
        }
    }

    // 设置表格单元格渲染器，使内容居中对齐
    private void setupTableRenderer() {
        DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
        centerRenderer.setHorizontalAlignment(JLabel.CENTER);
        table.setDefaultRenderer(Object.class, centerRenderer);
    }
}